package com.bw.common.mvi

import android.os.Bundle
import androidx.databinding.ViewDataBinding
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import com.bw.common.base.BaseActivity
import com.bw.common.event.CustomEvent
import kotlinx.coroutines.launch
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

abstract class BaseMviActivity<T:ViewDataBinding>:BaseActivity<T>() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        //初始化数据
        initData()
        //更新ui
        updateUi()
        //注册EventBus
        EventBus.getDefault().register(this)

    }
        @Subscribe(threadMode = ThreadMode.MAIN)
        fun receiveEvent(event:CustomEvent){
            if(event!=null&& event.terget==this::class.java.simpleName){
                handEvent(event)
            }
        }

    open fun handEvent(event: CustomEvent){

    }

    override fun onDestroy() {
        EventBus.getDefault().unregister(this)
        super.onDestroy()

    }
    private fun updateUi(){
        //启动协程更新ui
        lifecycleScope.launch {
            //当页面能看见的时候，渲染发生的时候，但是还没有获取焦点(在之前没必要)
            lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED){
                collectUiState()
            }
        }
    }

    open suspend fun collectUiState(){

    }

    private fun initData(){
        //启动协程给viewmodel发送意图intent
        lifecycleScope.launch {
            sendViewIntent()
        }
    }

    open suspend fun sendViewIntent(){

    }

}